package com.offcn.common.utils;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

/**
 * @Auther: lhq
 * @Date: 2021/11/23 14:12
 * @Description: JWT令牌工具类
 */
public class JWTUtil {

    private static final String SECRET_KEY = "u-member-offcn123"; //秘钥
    public static final long TOKEN_EXPIRE_TIME = 5 * 60 * 1000; //token过期时间
    public static final long REFRESH_TOKEN_EXPIRE_TIME = 10 * 60 * 1000; //refreshToken过期时间
    private static final String ISSUER = "offcn"; //签发人

    //生成令牌
    public static String createJWT(String username) {
        String id = UUID.randomUUID().toString().replace("-", "");
        JwtBuilder jwtBuilder = Jwts.builder().setId(id)
                .setIssuer(ISSUER)
                .setIssuedAt(new Date())
                .setExpiration(new Date(new Date().getTime() + TOKEN_EXPIRE_TIME))
                .claim("username", username)
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY);
        String token = jwtBuilder.compact();
        return token;
    }


    //校验令牌
    public  static boolean checkJWT(String token){
        try {
            parseJWT(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }



    //解析令牌
    public static Claims parseJWT(String token){
        Claims claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
        return claims;
    }

    /**
     * 通过令牌得到用户信息
     * @param token
     * @return
     */
    public static String getUsername(String token){
        Claims claims = parseJWT(token);
        String  username =(String) claims.get("username");
        return username;
    }
}
